package com.maya.screens;

import java.util.Timer;
import java.util.TimerTask;


import com.maya.R;
import com.maya.scoresUtility.ScoresManager;
import com.maya.scoresUtility.ScoresManagerFactory;
import com.maya.utilities.Utilities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class GameScreenSinglePlayer extends Activity implements OnClickListener
{
	static int[] sayi; 
	static int[] thmn; 
	static String arananSayi = "";
	static int dogru_yer = 0;
	static int dogru_sayi = 0;
	static int tahmin_sayisi = 0;
	static int tahmin_suresi = 0;
	static int kalanSure;
	static int birTahminIcinMaxSure;
	static int toplam_gecen_sure = 0;
	static boolean buttonTryIsPressed = false;
	static int zorlukSeviyesi = 2;
	static String zorluk = "";

	int kullanici_tahmini = -1;
	int basamakSayisi = Constants.BASAMAK_SAYISI_NORMAL_DUZEY;
	
	private TextView textViewGuess;
	private Button buttonTry;
	private TextView textViewRemainingTime;
	private ProgressBar progressBar;
	private TextView textViewTotalTime;
	private TextView textViewPreviousGuesses1;
	private TextView textViewPreviousGuesses2;
	private Button buttonNewGame;
	private Button buttonMainScreen;
	private EditText textEntryName;
	private TextView textEntryNameLabel;
	
	private Resources res = null;
	private Timer timer;
	Utilities util = new Utilities();
	PreferencesScreen pref = new PreferencesScreen();
	BestScoresScreen best = new BestScoresScreen();
	
	private MediaPlayer sound;
	private boolean soundIsOn = true;
	
	private int puan = 0;
	
	private ScoresManager scoresManager;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		res = this.getResources();
		
		basamakSayisi = pref.getBasamakSayisi(getApplicationContext());
		birTahminIcinMaxSure = pref.getMaxTahminSuresi(getApplicationContext());
		kalanSure = birTahminIcinMaxSure; 
		
		zorlukSeviyesi = pref.getZorlukSeviyesi(getApplicationContext());
		switch(zorlukSeviyesi)
		{
			case Constants.ZORLUK_SEVIYESI_KOLAY:
				zorluk = res.getString(R.string.Easy);
				break;
			case Constants.ZORLUK_SEVIYESI_NORMAL:
				zorluk = res.getString(R.string.Medium);
				break;
			case Constants.ZORLUK_SEVIYESI_ZOR:
				zorluk = res.getString(R.string.Hard);
				break;
			default:
				zorluk = res.getString(R.string.Medium);
				break;
		
		}
			
		sayi = new int[basamakSayisi];
		thmn = new int[basamakSayisi];
		
		sayiYarat();	
		
		if(pref.getSoundPreference(getApplicationContext())!=0)
			soundIsOn = true;
		else
			soundIsOn = false;
		
		super.onCreate(savedInstanceState);
        setContentView(R.layout.game);
        
        
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
             
        textViewGuess = (TextView) findViewById(R.id.editTextGuess);
        textViewGuess.requestFocus();
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(basamakSayisi);
        textViewGuess.setFilters(FilterArray);
        textViewGuess.setHint(R.string.GuessHint);
                
        buttonTry = (Button) findViewById(R.id.buttonTry);
        buttonTry.setOnClickListener(this);
        
        textViewRemainingTime = (TextView) findViewById(R.id.textViewRemainingTime);
        textViewRemainingTime.setText("");
        textViewRemainingTime.setTextAppearance(this, android.R.style.TextAppearance_Small);
        
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
    	progressBar.setProgressDrawable(res.getDrawable(R.drawable.progress));
    	progressBar.setMax(birTahminIcinMaxSure);
    	progressBar.setVisibility(View.INVISIBLE);
    	
   
        textViewTotalTime = (TextView) findViewById(R.id.textViewTotalTime);
        textViewTotalTime.setText("");
        textViewTotalTime.setTextAppearance(this, android.R.style.TextAppearance_Small);
        
        textViewPreviousGuesses1 = (TextView) findViewById(R.id.textViewPreviousGuesses1);
        textViewPreviousGuesses1.setText("");
        textViewPreviousGuesses1.setTextColor(Color.argb(255,0,255,128)); // Color.CYAN
        
        textViewPreviousGuesses2 = (TextView) findViewById(R.id.textViewPreviousGuesses2);
        textViewPreviousGuesses2.setText("");
        textViewPreviousGuesses2.setTextColor(Color.argb(255,0,255,128));
        
        buttonNewGame = (Button)findViewById(R.id.buttonNewGame);
        buttonNewGame.setOnClickListener(this);
        
        buttonMainScreen = (Button)findViewById(R.id.buttonMainScreen);
        buttonMainScreen.setOnClickListener(this);
        
        scoresManager = ScoresManagerFactory.getScoresManager(getApplicationContext());
        
    }
	
	@Override
	public void onBackPressed() 
	{
		finish();		
		if (buttonTryIsPressed)
		{	
			timer.cancel();
			timer.purge();
		}
		
		yeniOyunaHazirla();
		
		startActivity(new Intent(GameScreenSinglePlayer.this, MainScreen.class));
	}
		
	public void onClick(View v) 
	{
		if(v == buttonTry) 
		{	
			if(!buttonTryIsPressed)
			{
				timer = new Timer();
				timer.schedule(new TimerTask(){ public void run(){guncelle();}}, 0, 1000);
				buttonTryIsPressed = true;		
				
				textViewRemainingTime.setVisibility(View.VISIBLE);
				progressBar.setVisibility(View.VISIBLE);
			    textViewTotalTime.setVisibility(View.VISIBLE);
			    textViewPreviousGuesses1.setVisibility(View.VISIBLE);
			    textViewPreviousGuesses2.setVisibility(View.VISIBLE);
			}
			
			try
			{
				kullanici_tahmini = Integer.parseInt(textViewGuess.getText().toString());
				
				progressBar.setProgress(0);
				tahmin_suresi = 0;
				kalanSure = birTahminIcinMaxSure;
				
				switch(basamakSayisi)
				{
					case Constants.BASAMAK_SAYISI_KOLAY_DUZEY:
						thmn[0] = (int)(kullanici_tahmini/100);
						thmn[1] = (int)((kullanici_tahmini%100)/10);
						thmn[2] = (int)(kullanici_tahmini%10); 
						break;
					
					case Constants.BASAMAK_SAYISI_NORMAL_DUZEY:
						thmn[0] = (int)(kullanici_tahmini/1000);
						thmn[1] = (int)((kullanici_tahmini%1000)/100);
						thmn[2] = (int)((kullanici_tahmini%100)/10);
						thmn[3] = (kullanici_tahmini%10);
						break;
						
					case Constants.BASAMAK_SAYISI_ZOR_DUZEY:
						thmn[0] = (int)(kullanici_tahmini/10000);
						thmn[1] = (int)((kullanici_tahmini%10000)/1000);
						thmn[2] = (int)((kullanici_tahmini%1000)/100);
						thmn[3] = (int)((kullanici_tahmini%100)/10);
						thmn[4] = (kullanici_tahmini%10);
						break;
						
					default:
						thmn[0] = (int)(kullanici_tahmini/1000);
						thmn[1] = (int)((kullanici_tahmini%1000)/100);
						thmn[2] = (int)((kullanici_tahmini%100)/10);
						thmn[3] = (kullanici_tahmini%10);
						break;
				
				}
							
				if(
				  ((basamakSayisi == Constants.BASAMAK_SAYISI_KOLAY_DUZEY)
					&&(thmn[0]==0||thmn[0]==thmn[1]||thmn[0]==thmn[2]||thmn[1]==thmn[2]))
				||((basamakSayisi == Constants.BASAMAK_SAYISI_NORMAL_DUZEY)
					&&(thmn[0]==0||thmn[0]==thmn[1]||thmn[0]==thmn[2]||thmn[0]==thmn[3]||thmn[1]==thmn[2]||thmn[1]==thmn[3]||thmn[2]==thmn[3]))
				||((basamakSayisi == Constants.BASAMAK_SAYISI_ZOR_DUZEY)
					&&(thmn[0]==0||thmn[0]==thmn[1]||thmn[0]==thmn[2]||thmn[0]==thmn[3]||thmn[0]==thmn[4]||thmn[1]==thmn[2]||thmn[1]==thmn[3]||thmn[1]==thmn[4]||thmn[2]==thmn[3]||thmn[2]==thmn[4]||thmn[3]==thmn[4]))
				  )
				{
					util.showToast(getApplicationContext(),R.string.ErrorInputGuess, 2000, Constants.ERROR_ICON_ID);
					
					if(soundIsOn)
					{
						util.playSound(sound, getApplicationContext(), R.raw.info);
					}
				}
				else
				{
					tahmin_sayisi++;
							
					for(int i = 0; i<basamakSayisi; i++)
					{
						for(int j = 0; j<basamakSayisi; j++)
						{
							if((sayi[i] == thmn[j]) && (i==j))
							{
								dogru_yer++;
								break;
							}
									
							if((sayi[i]==thmn[j]) && (i!=j))
							{
								dogru_sayi++;
								break;
							}
						}
									
					}
					
					String s = res.getString(R.string.nThGuess);
					
					if(tahmin_sayisi<6)
					{
						textViewPreviousGuesses1.append(tahmin_sayisi+s+ " " + textViewGuess.getText().toString());
						
						if(dogru_yer==0 && dogru_sayi==0)
							textViewPreviousGuesses1.append("\t0\n");
						else if(dogru_yer==0 && dogru_sayi!=0)
							textViewPreviousGuesses1.append("\t-"+dogru_sayi+"\n");
						else if(dogru_yer!=0 && dogru_sayi==0)
							textViewPreviousGuesses1.append("\t+"+dogru_yer+"\n");
						else if(dogru_yer!=0 && dogru_sayi!=0)
							textViewPreviousGuesses1.append("\t+"+dogru_yer+"  "+"-"+dogru_sayi+"\n");						
						
					}
					else
					{
						textViewPreviousGuesses2.append(tahmin_sayisi+s+ " " + textViewGuess.getText().toString());
						
						if(dogru_yer==0 && dogru_sayi==0)
							textViewPreviousGuesses2.append("\t0\n");
						else if(dogru_yer==0 && dogru_sayi!=0)
							textViewPreviousGuesses2.append("\t-"+dogru_sayi+"\n");
						else if(dogru_yer!=0 && dogru_sayi==0)
							textViewPreviousGuesses2.append("\t+"+dogru_yer+"\n");
						else if(dogru_yer!=0 && dogru_sayi!=0)
							textViewPreviousGuesses2.append("\t+"+dogru_yer+"  "+"-"+dogru_sayi+"\n");					
					}
					
					
					if(dogru_yer==basamakSayisi)
					{
						puan = puanHesapla();
						String Kazandiniz = res.getString(R.string.winGame, tahmin_sayisi, toplam_gecen_sure, puan);
						oyunBitir(Kazandiniz, puan);
						if(soundIsOn)
						{
							util.playSound(sound, getApplicationContext(), R.raw.applause);
						}
					}
					else if(tahmin_sayisi==Constants.TAHMIN_HAKKI)
					{
						String Kaybettiniz = res.getString(R.string.lostGame);
						oyunBitir(Kaybettiniz+arananSayi+"", puan);
						if(soundIsOn)
						{
				        	util.playSound(sound, getApplicationContext(), R.raw.lost);
						}
					}
					dogru_yer = 0;
					dogru_sayi = 0;
				}
			}catch(NumberFormatException nfe)
			{
				util.showToast(getApplicationContext(),R.string.ErrorInputGuess, 2000, Constants.ERROR_ICON_ID);
				if(soundIsOn)
				{
					util.playSound(sound, getApplicationContext(), R.raw.info);
				}
			}
							
			textViewGuess.setText("");
			textViewGuess.setFocusable(true);
			
		}
		else if(v == textViewGuess)
		{
	        getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
		}
		else if (v == buttonNewGame) 
		{
			if (buttonTryIsPressed)
			{	
				timer.cancel();
				timer.purge();
			}
			
			yeniOyunBaslat();
		}
		else if (v == buttonMainScreen) 
		{
			if (buttonTryIsPressed)
			{	
				timer.cancel();
				timer.purge();
			}
			
			yeniOyunaHazirla();
			
			startActivity(new Intent(GameScreenSinglePlayer.this, MainScreen.class));
		}		
	}
	
	public void sayiYarat()
	{
		int s=0;
		
		if(basamakSayisi == Constants.BASAMAK_SAYISI_KOLAY_DUZEY)
		{
			// Yuzler basamagi
			for(int i=0;i<100;i++){s=(int)(Math.random()*10);if(s!=0){sayi[0]=s; break;}}
			for(int i=0;i<100;i++){s=(int)(Math.random()*10);if(s!=sayi[0]){sayi[1]=s; break;}}
			for(int i=0;i<100;i++){s=(int)(Math.random()*10);if((s!=sayi[0])&&(s!=sayi[1])){sayi[2]=s; break;}}
			
			arananSayi += sayi[0]+""+sayi[1]+""+sayi[2];
		}
		else if (basamakSayisi == Constants.BASAMAK_SAYISI_NORMAL_DUZEY)
		{
			// Binler basamagi
			for(int i=0;i<1000;i++){s=(int)(Math.random()*10);if(s!=0){sayi[0]=s; break;}}
			for(int i=0;i<1000;i++){s=(int)(Math.random()*10);if(s!=sayi[0]){sayi[1]=s; break;}}
			for(int i=0;i<1000;i++){s=(int)(Math.random()*10);if((s!=sayi[0])&&(s!=sayi[1])){sayi[2]=s; break;}}
			for(int i=0;i<100;i++){s=(int)(Math.random()*10);if((s!=sayi[0])&&(s!=sayi[1])&&(s!=sayi[2])){sayi[3]=s;}}
			
			arananSayi += sayi[0]+""+sayi[1]+""+sayi[2]+""+sayi[3];
		}
		else if (basamakSayisi == Constants.BASAMAK_SAYISI_ZOR_DUZEY)
		{
			// On binler basamagi
			for(int i=0;i<100;i++){s=(int)(Math.random()*10);if(s!=0){sayi[0]=s; break;}}			
			for(int i=0;i<1000;i++){s=(int)(Math.random()*10);if(s!=sayi[0]){sayi[1]=s; break;}}
			for(int i=0;i<1000;i++){s=(int)(Math.random()*10);if((s!=sayi[0])&&(s!=sayi[1])){sayi[2]=s; break;}}
			for(int i=0;i<1000;i++){s=(int)(Math.random()*10);if((s!=sayi[0])&&(s!=sayi[1])&&(s!=sayi[2])){sayi[3]=s; break;}}
			for(int i=0;i<1000;i++){s=(int)(Math.random()*10);if((s!=sayi[0])&&(s!=sayi[1])&&(s!=sayi[2])&&(s!=sayi[3])){sayi[4]=s;}}
			
			arananSayi += sayi[0]+""+sayi[1]+""+sayi[2]+""+sayi[3]+""+sayi[4];
		}
	}
	
	public int puanHesapla()
	{
		int katsayi = 250000;
		
		switch(zorlukSeviyesi)
		{
			case Constants.ZORLUK_SEVIYESI_KOLAY:
				katsayi *= 1;
				break;
				
			case Constants.ZORLUK_SEVIYESI_NORMAL:
				katsayi *= 8;
				break;
				
			case Constants.ZORLUK_SEVIYESI_ZOR:
				katsayi *= 64;
				break;
				
			default:
				katsayi *= 8;
				break;		
		}
	    return katsayi/(tahmin_sayisi*toplam_gecen_sure);
	}
	
	public void progressBarIslemleri()
	{	 
		progressBar.setVisibility(View.VISIBLE);
		progressBar.setProgress(tahmin_suresi);
	}
	
	public void yeniOyunBaslat()
	{
		yeniOyunaHazirla();
		sayiYarat();	
			
		util.showToast(getApplicationContext(),R.string.NewGameCreated, 1000, Constants.INFO_ICON_ID);
		if(soundIsOn)
		{
			util.playSound(sound, getApplicationContext(), R.raw.info);
		}
	}
	
	public void oyunBitir(String s, final int score)
	{
		timer.cancel();
		timer.purge();
		
		String header =""; 
					        		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setCancelable(false);
		dialog.setMessage(s);
		
		if(score == 0)
		{
			header = res.getString(R.string.lostGameLabel);
			dialog.setTitle(header);
			dialog.setIcon(R.drawable.sadness);
			
			dialog.setNeutralButton(R.string.OK, new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			    	  yeniOyunBaslat();
			      }			      
			    });
		}
		else
		{
			LayoutInflater factory = LayoutInflater.from(this);
		    final View textEntryPrompt = factory.inflate(R.layout.bestscores_prompt, null);
		    
		    textEntryNameLabel = (TextView) textEntryPrompt.findViewById(R.id.bestscores_username_label);
		    
		    textEntryName = (EditText) textEntryPrompt.findViewById(R.id.players_name);
		    textEntryName.setBackgroundColor(Color.LTGRAY);
		    textEntryName.setTextColor(Color.BLACK);
		    	    
		    dialog.setView(textEntryPrompt);
		    
			header = res.getString(R.string.winGameLabel);
			dialog.setTitle(header);
			dialog.setIcon(R.drawable.happiness);
					
			if (scoresManager.isHighScore("Grup", score)) 
			{
				textEntryName.setVisibility(View.VISIBLE);
				textEntryNameLabel.setVisibility(View.VISIBLE);
				
				dialog.setNeutralButton(R.string.OK, new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {				    	 
						String name = textEntryName.getText().toString();
	                   
						scoresManager.addScore("Grup", name, score);
						
						SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
						SharedPreferences.Editor editor = preferences.edit();
						editor.putString("players_name", name);
						editor.commit();
						
						yeniOyunBaslat();
				      }
				    });
			}
			else
			{
				dialog.setNeutralButton(R.string.OK, new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
						yeniOyunBaslat();
				      }
				    });			
			}			
		}
		
		dialog.create().show();
	}
	
	public void yeniOyunaHazirla()
	{
		textViewGuess.setText("");
		textViewRemainingTime.setText("");
		textViewRemainingTime.setVisibility(View.INVISIBLE);
		progressBar.setProgress(0);
	    progressBar.setVisibility(View.INVISIBLE);
	    textViewTotalTime.setText("");
	    textViewTotalTime.setVisibility(View.INVISIBLE);
	    textViewPreviousGuesses1.setText("");
	    textViewPreviousGuesses1.setVisibility(View.INVISIBLE);
	    textViewPreviousGuesses2.setText("");
	    textViewPreviousGuesses2.setVisibility(View.INVISIBLE);
	    
	    toplam_gecen_sure = 0;
		tahmin_suresi = 0; 
		tahmin_sayisi = 0;
		kalanSure = birTahminIcinMaxSure;
		
		arananSayi = "";
		puan = 0;
		
		buttonTryIsPressed = false;
	}
	
	private void guncelle()
	{
		this.runOnUiThread(Timer_Tick);
	}

	private Runnable Timer_Tick = new Runnable() 
	{
		public void run() 
		{  	       
			if(tahmin_suresi==birTahminIcinMaxSure)
			{
				String Kaybettiniz = res.getString(R.string.lostGameDueToTime);
				oyunBitir(Kaybettiniz+arananSayi+"\n", puan);
				if(soundIsOn)
				{
		        	util.playSound(sound, getApplicationContext(), R.raw.lost);
				}
			}
			else
			{
				toplam_gecen_sure = toplam_gecen_sure+1;
				tahmin_suresi = tahmin_suresi+1; 
				kalanSure = birTahminIcinMaxSure-tahmin_suresi;
				
				String msg1 = res.getString(R.string.RemainingTime, kalanSure);
				textViewRemainingTime.setText(msg1);
				String msg2 = res.getString(R.string.TotalTime, toplam_gecen_sure);
				textViewTotalTime.setText(msg2);
				
				progressBarIslemleri();					
			}
		}
	};
}